extern "C" {
#include <pthread.h>
#include <stdarg.h>
#include <time.h>
}
#include "logger.hpp"

namespace logger {

  static   pthread_mutex_t g_log_mutex = PTHREAD_MUTEX_INITIALIZER;
  static   FILE*           g_log = stderr;

  void log(const char* level, const char* file, const int line, const char* format, ... ) {
    time_t tt;
    time(&tt);
    tm date;
    localtime_r(&tt, &date);
    char __buf[30];
    strftime(__buf, sizeof(__buf)-1, "%Y/%m/%d %H:%M:%S", &date);
    const int id = static_cast<int>(pthread_self());
    {
      pthread_mutex_lock(&g_log_mutex);
      fprintf(g_log, "%s [%s] thread:%d (%s %d): ", __buf, level, id, file, line);
      va_list vl;
      va_start(vl, format);
      vfprintf(g_log, format, vl);
      va_end(vl);
      fprintf(g_log, "\n");
      pthread_mutex_unlock(&g_log_mutex);
    }
  }
}

